goog.provide('gjslint.startup');

goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.forms');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.net.XhrIo');
goog.require('goog.ui.Component');
goog.require('gjslint.ErrorEntry');

gjslint.startup = function() {
  var form = goog.dom.getElement('lint_form');
  goog.events.listen(form, 'submit',
      gjslint.startup.handleForm_);
	
};

goog.exportSymbol('_gjslintstartup', gjslint.startup);

gjslint.startup.handleForm_ = function(e) {
  e.preventDefault();
  
  var form = e.target;
  var dataString = goog.dom.forms.getFormDataString(form);

  goog.net.XhrIo.send('/lint', gjslint.startup.handleLint_, 'POST', dataString);
};

gjslint.startup.handleLint_ = function(e) {
  var json = e.target.getResponseJson();				

  var resultsDiv = goog.dom.getElement('results');
  goog.dom.removeChildren(resultsDiv);
  
  var jsonErrors = json['errors'];
  
  var title = goog.dom.createDom('h4', null, 'Errors found: ' + jsonErrors.length);
  goog.dom.appendChild(resultsDiv, title);

  var errorComponent = new goog.ui.Component();
  errorComponent.render(resultsDiv);
  
  goog.array.forEach(jsonErrors, function(errorJson) {
    var error = new gjslint.ErrorEntry(errorJson);		       
    errorComponent.addChild(error, true);
  });
};